﻿package common {
	import common.KeyCode;
	import common.Scene;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.KeyboardEvent;
	import flash.ui.Keyboard;
	import main.MainScene;
	import map.MapScene;
	
	/**
	 * メインのスプライト
	 */
	public class MainSprite extends Sprite {
		public function MainSprite():void {
			if (stage) init();
			else addEventListener(Event.ADDED_TO_STAGE, init);
		}
		
		private function init(e:Event = null):void {
			removeEventListener(Event.ADDED_TO_STAGE, init);
			// entry point
			
			stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown);
			stage.addEventListener(KeyboardEvent.KEY_UP, onKeyUp);
			
			mapScene = new MapScene(this);
			mainScene = new MainScene(this);
			invokeMapScene(true, false);
		}
		
		private function onKeyDown(event:KeyboardEvent):void {
			switch (event.keyCode) {
				case Keyboard.LEFT:
					currentScene.onKeyDown(KeyCode.LEFT);
					break;
				case Keyboard.UP:
					currentScene.onKeyDown(KeyCode.UP);
					break;
				case Keyboard.RIGHT:
					currentScene.onKeyDown(KeyCode.RIGHT);
					break;
				case Keyboard.DOWN:
					currentScene.onKeyDown(KeyCode.DOWN);
					break;
				case Keyboard.ENTER:
					currentScene.onKeyDown(KeyCode.OK);
					break;
				case Keyboard.BACKSPACE:
				case Keyboard.ESCAPE:
					currentScene.onKeyDown(KeyCode.CANCEL);
					break;
			}
		}
		
		private function onKeyUp(event:KeyboardEvent):void {
			switch (event.keyCode) {
				case Keyboard.LEFT:
					currentScene.onKeyUp(KeyCode.LEFT);
					break;
				case Keyboard.UP:
					currentScene.onKeyUp(KeyCode.UP);
					break;
				case Keyboard.RIGHT:
					currentScene.onKeyUp(KeyCode.RIGHT);
					break;
				case Keyboard.DOWN:
					currentScene.onKeyUp(KeyCode.DOWN);
					break;
				case Keyboard.ENTER:
					currentScene.onKeyUp(KeyCode.OK);
					break;
				case Keyboard.BACKSPACE:
				case Keyboard.ESCAPE:
					currentScene.onKeyUp(KeyCode.CANCEL);
					break;
			}
		}
		
		/**
		 * メインのゲームシーンに移行します。
		 * @param	origin 始点のID
		 * @param	desination 終点のID
		 */
		public function invokeMainScene(origin:uint, desination:uint):void {
			if (currentScene == mapScene) {
				removeChild(mapScene.sprite);
			}
			addChild(mainScene.sprite);
			mainScene.init(origin, desination);
			currentScene = mainScene;
		}
		
		/**
		 * マップのゲームシーンに移行します。
		 */
		public function invokeMapScene(isFirst:Boolean, isGoaled:Boolean):void {
			if (currentScene == mainScene) {
				removeChild(mainScene.sprite);
			}
			addChild(mapScene.sprite);
			mapScene.init(isFirst, isGoaled);
			currentScene = mapScene;
		}
		
		private var currentScene:Scene;
		private var mapScene:MapScene;
		private var mainScene:MainScene;
	}
	
}
